package com.qilu.pe.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.ItemSet;
import com.qilu.pe.dao.bean.OrderDetail;
import com.qilu.pe.dao.bean.RefreshEvent;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.ui.adapter.ComboCardHolder;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 订单详情
public class OrderDetailActivity extends Base2Activity {
    private TextView tv_in_pay, tv_time_title, tv_discount_title, tv_discount_title2, tv_total_title, tv_time_title2, tv_pay_type_title, tv_order_no_title;
    private TextView tv_name, tv_age, tv_sex, tv_phone, tv_time, tv_time2, tv_pay_type;// 患者信息
    private TextView tv_test_price, tv_discount, tv_discount2, tv_freight, tv_coupon, tv_item_total;// 支付信息
    private TextView tv_price, tv_order_no;
    private TextView tv_sample_time, tv_sample_time2, tv_sel_sample_time;
    private EditText et_clinic_diag, et_remark;
    private TextView et_clinic_diag2, et_remark2;
    private RecyclerView rcv_item, rcv_sample_consemu;// 项目列表,套餐列表,样本耗材列表
    private TextView tv_cancel, tv_ok, vRefund, vRefundStatus;
    private CardView cv_item, vExtraInfoContainer2;
    private LinearLayout vSetContainer, vExtraInfoContainer;
    RelativeLayout rl_bottom;
    private List<ComboCardHolder> mSetCards = new ArrayList<>();
    private String[] mPayTypeArray = new String[]{"", "微信支付", "支付宝支付", "银联支付", "余额支付"};

    private ItemListAdapter itemAdapter;// 项目列表adapter
    private SampleAndConsumeListAdapter sampleAdapter;// 耗材adapter

    private String title = "订单详情";
    private String orderId;
    private String orderStatus;// 订单类型 订单状态 1 待付款,2 申请退款,3 订单取消,4 已退款,5 未接单,6 运输中,7 检验中,8 已出报告
    String mSamp_date = "";// 采样日期
    String mSamp_time = "";// 采样时间

    private OrderDetail detail;
    private String orderNum;// 订单号

    IWXAPI msgApi;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_order_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        tv_in_pay = findViewById(R.id.tv_in_pay);
        tv_name = findViewById(R.id.tv_name);
        tv_age = findViewById(R.id.tv_age);
        tv_sex = findViewById(R.id.tv_sex);
        tv_phone = findViewById(R.id.tv_phone);
        tv_time = findViewById(R.id.tv_time);
        tv_test_price = findViewById(R.id.tv_test_price);
        tv_discount = findViewById(R.id.tv_discount);
        tv_freight = findViewById(R.id.tv_freight);
        tv_coupon = findViewById(R.id.tv_coupon);
        tv_item_total = findViewById(R.id.tv_item_total);
        tv_price = findViewById(R.id.tv_price);
        tv_sample_time = findViewById(R.id.tv_sample_time);
        tv_sel_sample_time = findViewById(R.id.tv_sel_sample_time);
        et_clinic_diag = findViewById(R.id.et_clinic_diag);
        et_remark = findViewById(R.id.et_remark);
        rcv_item = findViewById(R.id.rcv_item);
        rcv_sample_consemu = findViewById(R.id.rcv_sample_consemu);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_ok = findViewById(R.id.tv_ok);
        cv_item = findViewById(R.id.cv_item);
        vSetContainer = findViewById(R.id.vSetContainer);
        tv_time_title = findViewById(R.id.tv_time_title);
        tv_discount_title = findViewById(R.id.tv_discount_title);
        tv_discount_title2 = findViewById(R.id.tv_discount_title2);
        tv_discount2 = findViewById(R.id.tv_discount2);
        tv_total_title = findViewById(R.id.tv_total_title);
        tv_time_title2 = findViewById(R.id.tv_time_title2);
        tv_time2 = findViewById(R.id.tv_time2);
        tv_pay_type_title = findViewById(R.id.tv_pay_type_title);
        tv_pay_type = findViewById(R.id.tv_pay_type);
        tv_order_no_title = findViewById(R.id.tv_order_no_title);
        tv_order_no = findViewById(R.id.tv_order_no);
        vExtraInfoContainer = findViewById(R.id.vExtraInfoContainer);
        vExtraInfoContainer2 = findViewById(R.id.vExtraInfoContainer2);
        et_clinic_diag2 = findViewById(R.id.et_clinic_diag2);
        et_remark2 = findViewById(R.id.et_remark2);
        tv_sample_time2 = findViewById(R.id.tv_sample_time2);
        rl_bottom = findViewById(R.id.rl_bottom);
        vRefund = findViewById(R.id.vRefund);
        vRefundStatus = findViewById(R.id.vRefundStatus);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            title = bundle.getString("title");
            orderId = bundle.getString("orderId");
            orderStatus = bundle.getString("orderStatus");
        }

        //已付款且不可退款，隐藏底部按钮
        if (!"5".equals(orderStatus)) {
            vRefund.setVisibility(View.GONE);
            if ("5678".indexOf(orderStatus) != -1) {
                rl_bottom.setVisibility(View.GONE);
            }
        } else if ("2".equals(orderStatus)) {
            //退款中
            vRefund.setVisibility(View.GONE);
            vRefundStatus.setVisibility(View.VISIBLE);
        } else {
            //已支付可退款
            vRefund.setVisibility(View.VISIBLE);
            vRefund.setOnClickListener(this);
        }

        handleViewByOrderType();

        tv_in_pay.setText(title);
        setHeadTitle(title);

        hideProgress();
        reqOrderDetail();
        showProgress();

        itemAdapter = new ItemListAdapter(this, orderStatus);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        rcv_item.setLayoutManager(manager);
        rcv_item.setAdapter(itemAdapter);

        sampleAdapter = new SampleAndConsumeListAdapter(this);
        LinearLayoutManager manager3 = new LinearLayoutManager(this);
        rcv_sample_consemu.setLayoutManager(manager3);
        rcv_sample_consemu.setAdapter(sampleAdapter);

        setListeners();
        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Config.WX_APP_ID);
    }

    // 根据订单类型 订单状态设置界面
    private void handleViewByOrderType() {
        // 订单状态 1 待付款,2 申请退款,3 订单取消,4 已退款,5 未接单,6 运输中,7 检验中,8 已出报告
        if (TextUtils.equals("1", orderStatus)) {// 待付款
            tv_cancel.setVisibility(View.VISIBLE);
            tv_ok.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals("2", orderStatus)) {// 申请退款
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("3", orderStatus)) {// 订单取消
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("4", orderStatus)) {// 已退款
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("5", orderStatus)) {// 未接单
            tv_price.setVisibility(View.GONE);
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("6", orderStatus)) {// 运输中
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("7", orderStatus)) {// 检验中
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else if (TextUtils.equals("8", orderStatus)) {// 已出报告
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        } else {
            tv_cancel.setVisibility(View.GONE);
            tv_ok.setVisibility(View.GONE);
        }
    }

    private Disposable reqOrderDetail() {
        return APIRetrofit.getDefault().reqOrderDetail(Global.HEADER, orderId)
                .compose(RxUtil.<BaseResult2<OrderDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<OrderDetail>>() {
                    @Override
                    public void accept(BaseResult2<OrderDetail> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            detail = result2.getData();
                            if (null != detail) {
                                setData2View();
                            }
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 设置页面数据
    private void setData2View() {
        OrderDetail.UserInfo user = detail.getUserInfo();
        if (null != user) {
            tv_name.setText(user.getName());
            tv_age.setText(user.getBirth());
            tv_sex.setText(TextUtils.equals("0", user.getSex()) ? "男" : "女");
            tv_phone.setText(user.getPhone());
        }

        OrderDetail.Order order = detail.getOrder();
        if (null != order) {
            orderNum = order.getOrder_num();// 保存订单号,支付的时候用到

            tv_time.setText(order.getTime());// 预约时间
            tv_time2.setText(order.getTime());// 预约时间
            tv_pay_type.setText(mPayTypeArray[order.getPay_status()]);
            tv_order_no.setText(order.getOrder_num());
            tv_test_price.setText("￥" + order.getMoney());
            tv_discount.setText("-￥" + order.getDiscount());
            tv_discount2.setText("-￥" + order.getDiscount());
            tv_freight.setText("￥" + order.getFreight());
//            tv_coupon.setText("￥" + order.get());// 10.24 优惠券无数据
            tv_coupon.setText("￥"+order.getTicket());
            tv_item_total.setText("￥" + order.getPrice());
            tv_price.setText("总价：¥" + order.getPrice());

            String[] timeArray = order.getSamp_time().split(" ");
            tv_sample_time.setText(timeArray[0]);
            tv_sample_time2.setText(order.getSamp_time());
            tv_sel_sample_time.setText(timeArray[1]);
            et_clinic_diag.setText(order.getDiagnose());
            et_clinic_diag2.setText(order.getDiagnose());
            et_remark.setText(order.getRemark());
            et_remark2.setText(order.getRemark());
        }


        List<OrderDetail.Project> projectList = detail.getProject();
        if (projectList != null && projectList.size() > 0) {
            itemAdapter.setDataList(projectList);
        } else {
            cv_item.setVisibility(View.GONE);
        }

        List<OrderDetail.Combo> comboList = detail.getCombo();
        if (!isDataEmpty(comboList)) {
            for (int i = 0; i < comboList.size(); i++) {
                addSetCardToLayout(comboList.get(i));
                mSetCards.get(i).setSetItem(comboList.get(i).getInfo());
            }
        }

        List<OrderDetail.SubData> sampleList = detail.getSubData();
        sampleAdapter.setDataList(sampleList);

        if ("5678".indexOf(orderStatus) != -1) {
            //已付款部分额外处理
            tv_time_title.setVisibility(View.GONE);
            tv_time.setVisibility(View.GONE);
            tv_discount_title.setVisibility(View.GONE);
            tv_discount.setVisibility(View.GONE);
            tv_discount_title2.setVisibility(View.VISIBLE);
            tv_discount2.setVisibility(View.VISIBLE);
            tv_total_title.setText("实付款:");
            tv_time_title2.setVisibility(View.VISIBLE);
            tv_time2.setVisibility(View.VISIBLE);
            tv_pay_type_title.setVisibility(View.VISIBLE);
            tv_pay_type.setVisibility(View.VISIBLE);
            tv_order_no_title.setVisibility(View.VISIBLE);
            tv_order_no.setVisibility(View.VISIBLE);
            vExtraInfoContainer.setVisibility(View.GONE);
            vExtraInfoContainer2.setVisibility(View.VISIBLE);
        } else {
            //非已付款部分隐藏已付款部分内容
            tv_time_title.setVisibility(View.VISIBLE);
            tv_time.setVisibility(View.VISIBLE);
            tv_discount_title.setVisibility(View.VISIBLE);
            tv_discount.setVisibility(View.VISIBLE);
            tv_discount_title2.setVisibility(View.GONE);
            tv_discount2.setVisibility(View.GONE);
            tv_time_title2.setVisibility(View.GONE);
            tv_time2.setVisibility(View.GONE);
            tv_pay_type_title.setVisibility(View.GONE);
            tv_pay_type.setVisibility(View.GONE);
            tv_order_no_title.setVisibility(View.GONE);
            tv_order_no.setVisibility(View.GONE);
            vExtraInfoContainer.setVisibility(View.VISIBLE);
            vExtraInfoContainer2.setVisibility(View.GONE);
        }
    }

    public void addSetCardToLayout(OrderDetail.Combo combo) {
        View v = LayoutInflater.from(this).inflate(R.layout.item_set_card, null, false);
        ComboCardHolder holder = new ComboCardHolder(this, orderId, orderStatus);
        holder.setItem(v, combo);
        mSetCards.add(holder);
        vSetContainer.addView(v);
    }

    private void setListeners() {
        setOnClickListener(tv_cancel, tv_sample_time, tv_sel_sample_time, tv_ok);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_cancel) {// 取消订单
            AlertUtil.showComDialog(this, "是否取消该订单?", new AlertUtil.OnAlertBtnClickListner() {
                @Override
                public void onConfirmClick() {
                    hideProgress();
                    reqCancelOrder();
                    showProgress();
                }

                @Override
                public void onCancelClick() {

                }
            });
        }
        if (v == tv_sample_time) {// 点击选择采样日期
            sample_type = 1;
            initDatePicker();
            pvTime.show();
        }
        if (v == tv_sel_sample_time) {// 点击选择采样时间
            sample_type = 2;
            initTimePicker();
            pvTime.show();
        }
        if (v == tv_ok) {// 去支付
            showDialog();
        }
        switch (v.getId()) {
            case R.id.vRefund:
                final NormalDialog dialog = new NormalDialog(this)
                        .isTitleShow(false)
                        .contentGravity(Gravity.CENTER)
                        .content("确定发起退款？");
                dialog.setOnBtnClickL(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        showProgress();
                        APIRetrofit.getDefault().refundMyOrder(Global.HEADER, orderId)
                                .compose(RxUtil.<BaseResult2>subIoObMain())
                                .subscribe(new Consumer<BaseResult2>() {
                                    @Override
                                    public void accept(BaseResult2 res) throws Exception {
                                        hideProgress();
                                        if (res.isSuccess()) {
                                            ToastUtils.showShort("申请退款成功");
                                            finish();
                                            EventBus.getDefault().post(new RefreshEvent("refundOrder", orderId));
                                        } else {
                                            ToastUtils.showShort(res.getMsg());
                                        }
                                    }
                                }, new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) throws Exception {
                                        hideProgress();
                                        throwable.printStackTrace();
                                        ToastUtils.showShort("退款失败");
                                    }
                                });
                    }
                });
                dialog.show();
                break;
        }
    }

    private Disposable reqCancelOrder() {
        return APIRetrofit.getDefault().cancelMyOrder(Global.HEADER, orderId)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            EventBus.getDefault().post(new RefreshEvent("cancelOrder", orderId));
                            finish();
                        }
                        ToastUtils.showShort(baseResult2.getMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("取消订单失败");
                    }
                });
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, this);
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayBalance(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            paySuc();
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayUpay(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayWx(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(orderNum)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqPlaceOrderPayAli(Global.HEADER, orderNum, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
        UPPayAssistEx.startPay(OrderDetailActivity.this, null, null, tn, MyApp.unionPayMode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            //显示支付结果
            paySuc();
        } else if (str.equalsIgnoreCase("fail")) {
            ToastUtils.showShort("银联支付失败");
        } else if (str.equalsIgnoreCase("cancel")) {
            ToastUtils.showShort("您取消了银联支付");
        }
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderDetailActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();

                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        startActivity(PaySuccessActivity.class);
        finish();
        EventBus.getDefault().post(new RefreshEvent("paySucc"));
    }

    // 项目adapter
    private class ItemListAdapter extends ListBaseAdapter<OrderDetail.Project> {

        private String orderStatus;

        public ItemListAdapter(Context context) {
            super(context);
        }

        public ItemListAdapter(Context context, String orderStatus) {
            super(context);
            this.orderStatus = orderStatus;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_confirm_order_item_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_price = holder.getView(R.id.tv_price);
            final TextView vRefund = holder.getView(R.id.vRefund);
            final TextView vRefundStatus = holder.getView(R.id.vRefundStatus);

            OrderDetail.Project item = mDataList.get(position);

            tv_name.setText(item.getName());
            tv_time.setText(item.getDay() + "个工作日");
            tv_price.setText("¥" + item.getPrice());

            if ("5".equals(orderStatus)) {
                if (item.getStatus() == 1) {
                    vRefundStatus.setVisibility(View.VISIBLE);
                    vRefundStatus.setText("退款中");
                } else if (item.getStatus() == 2) {
                    vRefundStatus.setVisibility(View.VISIBLE);
                    vRefundStatus.setText("已退款");
                } else {
                    vRefund.setVisibility(View.VISIBLE);
                    vRefund.setTag(item);
                    vRefund.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(final View v) {
                            final NormalDialog dialog = new NormalDialog(mContext)
                                    .isTitleShow(false)
                                    .contentGravity(Gravity.CENTER)
                                    .content("确定发起退款？");
                            dialog.setOnBtnClickL(new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                }
                            }, new OnBtnClickL() {
                                @Override
                                public void onBtnClick() {
                                    dialog.dismiss();
                                    showProgress();
                                    APIRetrofit.getDefault().refundMyOrderItem(Global.HEADER, orderId, ((OrderDetail.Project) v.getTag()).getId())
                                            .compose(RxUtil.<BaseResult2>subIoObMain())
                                            .subscribe(new Consumer<BaseResult2>() {
                                                @Override
                                                public void accept(BaseResult2 res) throws Exception {
                                                    hideProgress();
                                                    if (res.isSuccess()) {
                                                        ToastUtils.showShort("申请退款成功");
                                                        vRefund.setVisibility(View.GONE);
                                                        vRefundStatus.setVisibility(View.VISIBLE);
                                                        vRefundStatus.setText("退款中");
                                                        EventBus.getDefault().post(new RefreshEvent("refundOrder", orderId));
                                                    } else {
                                                        ToastUtils.showShort(res.getMsg());
                                                    }
                                                }
                                            }, new Consumer<Throwable>() {
                                                @Override
                                                public void accept(Throwable throwable) throws Exception {
                                                    hideProgress();
                                                    throwable.printStackTrace();
                                                    ToastUtils.showShort("退款失败");
                                                }
                                            });
                                }
                            });
                            dialog.show();
                        }
                    });
                }
            }
        }
    }

    // 耗材adapter
    private class SampleAndConsumeListAdapter extends ListBaseAdapter<OrderDetail.SubData> {

        public SampleAndConsumeListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_sample_and_consume_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_consume = holder.getView(R.id.tv_consume);
            TextView tv_num = holder.getView(R.id.tv_num);
            TextView tv_name1 = holder.getView(R.id.tv_name1);
            TextView tv_name2 = holder.getView(R.id.tv_name2);
            TextView tv_name3 = holder.getView(R.id.tv_name3);
            TextView tv_hint = holder.getView(R.id.tv_hint);
            TextView tv_hint_info = holder.getView(R.id.tv_hint_info);
            RoundedImageView iv_sample_img = holder.getView(R.id.iv_sample_img);

            OrderDetail.SubData consume = mDataList.get(position);

            tv_consume.setText("耗材：" + consume.getSupplies());
            tv_num.setText("×" + consume.getCount());
            tv_name1.setText(consume.getSample());
            tv_name2.setText(TextUtils.equals("1", consume.getType()) ? "常温" : "冷藏");
            tv_name3.setText(consume.getCapacity());
            tv_hint_info.setText(consume.getSampling() == null ? "无" : consume.getSampling());
            GlideUtil.loadImg(Config.URL_IMG + consume.getPicture(), iv_sample_img);
        }
    }

    private TimePickerView pvTime;
    private int sample_type = 1;// 时间选择器的类型 1 日期 2 时间

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mSamp_time = getTime(date);
                tv_sel_sample_time.setText(mSamp_time);
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{false, false, false, true, true, true})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择时间")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private void initDatePicker() {//Dialog 模式下，在底部弹出
        // 注意月份 0-11代表1-12月份
//        int year = Calendar.getInstance().get(Calendar.YEAR);
//        int sMonth = Calendar.getInstance().get(Calendar.MONTH);
//        int sDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        Calendar startDate = Calendar.getInstance();
//        startDate.set(year, sMonth, sDay);

        Date orderDate = new Date();
        try {
            orderDate = new SimpleDateFormat(Config.TIME_FORMATE).parse(detail.getOrder().getTime() + " 23:59:59");
            if (orderDate.before(startDate.getTime())) {
                Calendar endDate = Calendar.getInstance();
                endDate.add(Calendar.DAY_OF_MONTH, 1);
                orderDate = endDate.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(orderDate);
        final Calendar finalDate = endDate;

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mSamp_date = getTime(date);
                tv_sample_time.setText(mSamp_date);
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择日期")
                .setRangDate(startDate, finalDate)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (sample_type == 1) {// 采样日期
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_YMD);
            return format.format(date);
        } else {// 采样时间
            SimpleDateFormat format = new SimpleDateFormat(Config.TIME_FORMATE_HMS);
            return format.format(date);
        }
    }

    @Override
    public void onBackPressed() {
        //未支付
        if ("1".equals(orderStatus)) {
            String[] timeArray = detail.getOrder().getSamp_time().split(" ");
            if (!tv_sample_time.getText().toString().equals(timeArray[0]) || !tv_sel_sample_time.getText().toString().equals(timeArray[1])
                    || (detail.getOrder().getDiagnose() != null && !et_clinic_diag.getText().toString().equals(detail.getOrder().getDiagnose()))
                    || (detail.getOrder().getDiagnose() == null && !et_clinic_diag.getText().toString().isEmpty())
                    || (detail.getOrder().getRemark() != null && !et_remark.getText().toString().equals(detail.getOrder().getRemark()))
                    || (detail.getOrder().getRemark() == null && !et_remark.getText().toString().isEmpty())) {
                showProgress();
                APIRetrofit.getDefault().editOrder(Global.HEADER, tv_sample_time.getText().toString(), et_clinic_diag.getText().toString(), et_remark.getText().toString(), orderId)
                        .compose(RxUtil.<BaseResult2>subIoObMain())
                        .subscribe(new Consumer<BaseResult2>() {
                            @Override
                            public void accept(BaseResult2 res) throws Exception {
                                hideProgress();
                                if (res.isSuccess()) {
                                    ToastUtils.showShort("保存成功");
                                } else {
                                    ToastUtils.showShort(res.getMsg());
                                }
                                OrderDetailActivity.super.onBackPressed();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                hideProgress();
                                throwable.printStackTrace();
                            }
                        });
            } else {
                OrderDetailActivity.super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }
}